package demo2;

import java.util.Arrays;

public class ArrayList {

    public int usedSize;
    public static final int DEFAULT_SIZE = 5;

    public int[] elem = new int[DEFAULT_SIZE];

    public void disPlay() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }

    public int size() {
        return this.usedSize;
    }

    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    public void addArray(int data) {
        if (isFull()) {
            this.elem = expansion(this.elem,2);
        }
        this.elem[usedSize] = data;
        this.usedSize = usedSize + 1;
    }

    public void addArray(int pos,int data) {
        checkIndex(pos);
        if (isFull()) {
            this.elem = expansion(this.elem,2);
        }
        for (int i = usedSize-1; i >= pos; i--) {
            elem[i+1] = elem[i];
        }
        this.elem[pos] = data;
        this.usedSize = usedSize + 1;
    }

    public void remove(int data) {
        int a = indexOf(data);
        if (a == -1) {
            System.out.println("没有找到该数据！");
            return;
        }
        for (int i = a; i < usedSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.usedSize = this.usedSize-1;
        this.elem[usedSize] = 0;
    }

    public boolean isFull() {
        return this.elem.length == this.usedSize;
    }

    public int getIndex(int pos) {
        checkGetIndex(pos);
        return this.elem[pos];
    }

    public void setIndex(int pos,int data) {
        checkIndex(pos);
        this.elem[pos]= data;
    }


    private void checkIndex(int pos) {
        if (pos < 0 || pos > usedSize) {
            throw new IndexOutOfException("选择位置不合法，请检查位置的合法性！！！");
        }
    }

    private void checkGetIndex(int pos) {
        if (pos < 0 || pos >= usedSize) {
            throw new IndexOutOfException("get元素时，选择位置不合法，请检查位置的合法性！！！");
        }
    }

    private int[] expansion(int[] array,int multiple) {
        return Arrays.copyOf(array,array.length*multiple);
    }

    public void clear() {
        this.usedSize = 0;
    }

}
